package mymongo

import (
    "fmt"
    "strings"
    "context"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo/options"
)
/* =================================================================================
   索引操作
*/
func createIndexIfNotExists(client *Curs) error {
    // 创建索引
    var indexes []mongo.IndexModel
	for _, key := range client.Body.Data {
		indexes = append(indexes, mongo.IndexModel{
			Keys: bson.D{{Key: "data." + key.Value, Value: 1}},
			Options: options.Index().SetName(fmt.Sprintf("data_%s_idx", key.Value)),
		})
	}
	if len(indexes) == 0 {
		return nil
	}
	client.Cur.Indexes().CreateMany(context.TODO(), indexes)
	return nil
}

func CreateSingleIndex(collection *mongo.Collection, data []string) (string, error) {
    // 创建索引
    if len(data) == 0 {
	    return "", fmt.Errorf("无法创建索引：字段列表为空")
	}
    indexKeys := bson.D{}
    for _, value := range data {
    	indexKeys = append(indexKeys, bson.E{Key: value, Value: 1})
    }
    idx := strings.Join(data, "_")
    indexOptions := options.Index().
        SetName(idx + "_idx").         // 指定索引名称
        SetUnique(false)               // 唯一性约束

    indexModel := mongo.IndexModel{
        Keys:    indexKeys,
        Options: indexOptions,
    }
    _, err := collection.Indexes().CreateOne(context.TODO(), indexModel)
    if err != nil {
        return "", fmt.Errorf("创建索引失败: %w", err)
    }
    return idx, nil
}

func DropSingleIndex(collection *mongo.Collection, indexName string) (bool, error) {
    // 删除指定名称的索引
    if indexName == "" {
	    return false, fmt.Errorf("无法删除索引：索引名称为空")
	}
    _, err := collection.Indexes().DropOne(context.TODO(), indexName)
    if err != nil {
        return false, fmt.Errorf("删除索引失败: %w", err)
    }
    return true, nil
}

func ListAllIndexes(collection *mongo.Collection) []bson.M {
	var indexes []bson.M
    cursor, err := collection.Indexes().List(context.TODO())
    if err != nil {
        return indexes
    }
    defer cursor.Close(context.TODO())
    cursor.All(context.TODO(), &indexes)
    return indexes
}